var typeLib = require('../type')
var pathLib = require('path')


var libEach = require('array-each')


/**
 * 遍历数组
 * @param  {[type]}   arr      [description]
 * @param  {Function} callback [description]
 * @param  {[type]}   thisArg  [description]
 * @return {[type]}            [description]
 */
function arrayEach(arr, callback, thisArg) {
	if(!Array.isArray(arr)) {
		throw new TypeError('Expects the first argument is an array')
	}

	var result = []
	for (var i = 0; i < arr.length; i++) {
		var ele = callback.call(thisArg, arr[i], i, arr)
		result.push(ele)
	}
	return result ;
}

/**
 * 可以遍历各种数据类型的 一个函数封装，
 * 可以返回值(具有一定map的功能, 没有判断回调函数的真假值)
 * @param  {[type]}   elem     [description]
 * @param  {Function} callback [description]
 * @param  {[type]}   thisArg  [description]
 * @return {[type]}            [description]
 */
function each(elem, callback, thisArg) {
	var result = [] 
	// 过滤掉 null/undefined
	if(elem == null) {
		return result
	}

	// 将标量变为数组 —— 可遍历的结构
	if(typeof elem !== 'object') {
		elem = [elem]
	}
	
	var oneRet ;
	if(Array.isArray(elem)) {
		for (var i = 0; i < elem.length; i++) {
			oneRet = callback.call(thisArg, elem[i], i, elem)
			result.push(oneRet)
		}
	} else {
		for(var i in elem) {
			if(elem.hasOwnProperty(i)) {
				oneRet = callback.call(thisArg, elem[i], i, elem)
				result.push(oneRet)
			}
		}
	}
	return result
}

 
var array = ['a', {a: 'b'}, 1, 'b', 2, {c: 'd'}, 'c']

function f1(ele) {
  return ele + ele;
}

function f2(ele, i) {
	console.log(ele)
	return `${i} : ${JSON.stringify(ele)}` ;
}

console.group('arr-each')
var ret = libEach(['a', 'b', 'c'], f1);

var ret = libEach(array, f2) 
console.groupEnd()

console.log('\n-----------------------\n')

console.group(pathLib.basename(__filename))

var ret11 = arrayEach(['a', 'b', 'c'], f1);

var ret12 = arrayEach(array, f2) 
console.groupEnd()

console.log('---------------------------------\n')

var ret21 = each(['a', 'b', 'c'], f1);
var ret22 = each(array, f2) 

console.log(JSON.stringify(ret11) === JSON.stringify(ret21) )
console.log(JSON.stringify(ret12) === JSON.stringify(ret22) )
